package gu.simplemq.redis;

import java.net.URI;
import java.net.URISyntaxException;

import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;

import redis.clients.jedis.Protocol;
import redis.clients.util.JedisURIHelper;

import static com.google.common.base.Preconditions.*;
import static redis.clients.jedis.Protocol.DEFAULT_DATABASE;
import static redis.clients.jedis.Protocol.DEFAULT_HOST;
import static redis.clients.jedis.Protocol.DEFAULT_PORT;

public class JedisURI {
	private final URI uri;
	public JedisURI(URI uri) {
		this.uri = JedisURI.normalized(checkNotNull(uri,"uri is null"));
	}
	public JedisURI(String uri) throws URISyntaxException {
		this(new URI(checkNotNull(Strings.emptyToNull(uri),"uri is null")));
	}
	public URI getUri() {
		return uri;
	}

	public String getHost(){
		return uri.getHost();
	}
	public int getPort(){
		return uri.getPort();
	}
	public String getPassword(){
		return JedisURIHelper.getPassword(uri);
	}
	public int getDatabase(){
		return JedisURIHelper.getDBIndex(uri);
	}
	private static String convertHost(String host) {
		if ("127.0.0.1".equals(host)) {
			return Protocol.DEFAULT_HOST;
		}
		else if ("::1".equals(host)) {
			return Protocol.DEFAULT_HOST;
		}
		
		return host;
	}
	/**
	 * 返回归一化的{@link URI}对象，such as jedis://192.168.1.100:6379/0<br>
	 * 如果没有指定host,则使用默认值{@link Protocol#DEFAULT_HOST},
	 * 如果没有指定port,则使用默认值{@link Protocol#DEFAULT_PORT},
	 * @param uri 为{@code null}返回 'jedis://localhost:6379/0'
	 */
	private static URI normalized(URI uri){
		try {
			if(null == uri){
				return URI.create(String.format("jedis://%s:%d/%d",DEFAULT_HOST,DEFAULT_PORT,DEFAULT_DATABASE));
			}
			return new URI("jedis", 
					uri.getUserInfo(), 
					MoreObjects.firstNonNull(JedisURI.convertHost(uri.getHost()),DEFAULT_HOST),
					uri.getPort() == -1 ? DEFAULT_PORT : uri.getPort(), 
					"/" + JedisURIHelper.getDBIndex(uri), 
					null, 
					null);
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}
}
